package co.fitstart.mobile.web.controller.profile;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.web.interceptor.WechatJsConfig;

import co.fitstart.entity.user.User;
import co.fitstart.entity.user.fit.Shape;
import co.fitstart.entity.user.fit.UserFit;
import co.fitstart.entity.user.investigation.FitInvestigation;
import co.fitstart.entity.user.investigation.HealthInvestigation;
import co.fitstart.entity.user.investigation.ParticipateInvestigation;
import co.fitstart.entity.user.investigation.ProfileInvestigation;
import co.fitstart.entity.user.profile.UserProfile;
import co.fitstart.mobile.handler.QrcodeHandler;
import co.fitstart.mobile.service.InvestigationService;
import co.fitstart.mobile.web.interceptor.MobileDetect;
import co.fitstart.mobile.web.interceptor.Router;
import co.fitstart.mobile.web.interceptor.WechatAuthority;
import co.fitstart.mobile.web.resolver.Secure;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("/investigations")
public class ProfileInvestigationController {
    
    private static final Logger logger = LoggerFactory.getLogger(ProfileInvestigationController.class);
    
    @Autowired
    private InvestigationService investigationService;
    
    @Autowired
    private QrcodeHandler qrcodeHandler;
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @Router
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public String index() {
        return "investigation/investigation-index";
    }
    
    /**
     * 
     * @param user
     * @return
     */
    @RequestMapping(value = "/profile", method = RequestMethod.GET)
    @Router
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public ModelAndView editProfile(@Secure User user) {
        
        ModelAndView modelAndView = new ModelAndView("investigation/profile-investigation");
        
        modelAndView.addObject("user", user);
        
        // load profile
        UserProfile userProfile = user.getProfile();
        if(userProfile != null) {
            modelAndView.addAllObjects(userProfile.describe());
        }
        
        return modelAndView;
    }
    
    /**
     * 
     * @param user
     * @param profileInvestigation
     * @param mediaId
     * @return
     */
    @Router
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    @RequestMapping(value = "/profile", method = RequestMethod.PATCH)
    public @ResponseBody String onEditProfile(@Secure User user, 
                                              ProfileInvestigation profileInvestigation,
                                              @RequestParam(value = "mediaId", required = false) String mediaId) {
        

        Result result = new Result();
        
        try {
            
            Result saveUserQrcodeResult = null;
            
            // Step1: if mediaId is not empty & userProfile's qrcodePath is empty, save qrcode file
            if(StringUtils.isEmpty(mediaId) && !user.hasQrcode()) {   // empty both, throw new error
                
                throw new BusinessException("请上传二维码");
            
            } else if (StringUtils.isEmpty(mediaId) && user.hasQrcode()) {
                user = qrcodeHandler.changeUserQrcode(user, profileInvestigation.getWechatCode());
                profileInvestigation.editQrcodePath(user.getWechat().getQrcode());
            }
            else if(StringUtils.isNotEmpty(mediaId)) { // empty qrcodePath, but not empty mediaTd, save file
                
                saveUserQrcodeResult = qrcodeHandler.saveUserQrcode(profileInvestigation.getWechatCode(), mediaId);
                if (saveUserQrcodeResult.isValid()) {
                    profileInvestigation.editQrcodePath(saveUserQrcodeResult.getData().get("fileName").toString());
                }
            }
            
            investigationService.editProfile(user, profileInvestigation);
            
            result.success().message("编辑基本信息成功");
            
        } catch (BusinessException e) {
            logger.error("onEditProfile() error", e);
            result.fail().message(e.getMessage());
            
        } catch (Exception e) {
            logger.error("onEditProfile() error", e);
            result.fail().message("编辑基本信息失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param user
     * @return
     */
    @RequestMapping(value = "/fit", method = RequestMethod.GET)
    @Router
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public ModelAndView editFit(@Secure User user) {
        
        ModelAndView modelAndView = new ModelAndView("investigation/fit-investigation");
        
        UserFit userFit = user.getUserFit() == null ? new UserFit() : user.getUserFit();
        modelAndView.addObject("userFit", userFit);
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param user
     * @param shapeId
     * @param fitInvestigation
     * @return
     */
    @RequestMapping(value = "/fit", method = RequestMethod.PATCH)
    @Router
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public @ResponseBody String onEditFit(@Secure User user,
                                          @RequestParam(value = "shapeId") Long shapeId,
                                          FitInvestigation fitInvestigation) {
        
        Result result = new Result();
        
        try {
            
            // edit fit's shape
            Shape shape = investigationService.loadShape(shapeId);
            
            investigationService.editFit(user, fitInvestigation, shape);
            
            result.success().message("编辑身体数据成功");
            
        } catch (Exception e) {
            
            logger.error("onEditFir() error", e);
            result.fail().message("编辑身体数据失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param user
     * @return
     */
    @RequestMapping(value = "/health", method = RequestMethod.GET)
    @Router
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public ModelAndView editHealth(@Secure User user) {
        
        ModelAndView modelAndView = new ModelAndView("investigation/health-investigation");
        
        HealthInvestigation healthInvestigation = investigationService.loadLastHealth(user);
        modelAndView.addObject("healthInvestigation", healthInvestigation);
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param user
     * @param healthInvestigation
     * @return
     */
    @RequestMapping(value = "/health", method = RequestMethod.PATCH)
    @Router
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public @ResponseBody String onEditHealth(@Secure User user,
                                             HealthInvestigation healthInvestigation) {
        
        Result result = new Result();
        
        try {
            
            investigationService.editHealth(user, healthInvestigation);
            
            result.success().message("编辑健康调查成功");
            
        } catch (Exception e) {
            
            logger.error("onEditHealth() error", e);
            
            result.fail().message("编辑健康调差失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param user
     * @return
     */
    @RequestMapping(value = "/participate", method = RequestMethod.GET)
    @Router
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public ModelAndView editParticipate(@Secure User user) {
        
        ModelAndView modelAndView = new ModelAndView("investigation/participate-investigation");
        
        ParticipateInvestigation participateInvestigation = investigationService.loadLastParticipate(user);
        modelAndView.addObject("participateInvestigation", participateInvestigation);
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param user
     * @param participateInvestigation
     * @return
     */
    @RequestMapping(value = "/participate", method = RequestMethod.PATCH)
    @Router
    @WechatAuthority
    @MobileDetect
    @WechatJsConfig
    public @ResponseBody String onEditParticipate(@Secure User user,
                                                  ParticipateInvestigation participateInvestigation) {
        
        Result result = new Result();
        
        try {
            
            investigationService.editParticipate(user, participateInvestigation);
            
            result.success().message("编辑其他调查成功");
            
        } catch (Exception e) {
            
            logger.error("onEditOther() error", e);
            
            result.fail().message("编辑其他调查失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
}
